

var http = require('http');
var path = require('path');
var express = require('express');
var bodyParser=require('body-parser');
var urlencodeParser = bodyParser.urlencoded({ extended: false })
var socketIo = require('socket.io');
var ejs = require('ejs');
var cookie = require('cookie-parser');
var session = require('express-session')


var fs = require('fs');

var app = express();

var server = http.createServer(app);
var io = socketIo(server);
app.use(session({
    secret: 'keyboard cat',
}))
app.use(cookie())

var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/chat');
mongoose.connection.on('connected',function(){
    console.log('数据库已连接');
   
})
var Schema=mongoose.Schema({
    name:String,
    chatInfo:String,
    time:String
})
var model=mongoose.model('chat',Schema);

var mongoose2 = require('mongoose');
mongoose2.connect('mongodb://localhost:27017/user');
mongoose2.connection.on('connected', function () {
    console.log('数据库已连接');

})
var Schema2 = mongoose2.Schema({
    username:String,
    password:String
})
var model2 = mongoose2.model('user', Schema2);

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.get('/',function(req,res) {
    res.sendFile(__dirname+'/views/index.html');
})
app.post('/login', urlencodeParser,function(req,res) {
    if(req.body){
        model2.find({ username: req.body.username }, function (err, result) {
            if (err) {
                console.log(err)
            } else {
                if (result) {
                    // res.render('client', { username: req.body.username });
                    req.session.username = req.body.username;
                    res.redirect('/client');
                } else {
                    res.send('登录失败')
                }
            }
        })
    }
})
app.post('/entro', urlencodeParser, function (req, res) {
    console.log(req.body);
    model2.create({username:req.body.username,password:req.body.password},function(err,result) {
        if (err) {
            console.log(err)
        } else {
            console.log(result);
            if (result) {
                // res.render('client', { username: req.body.username });
                req.session.username = req.body.username;
                res.redirect('/client')
            } else {
                res.send('注册失败')
            }
        }
    })
})
app.get('/client', function (req, res) {
    var username = req.session.username;
    if (req.session.username == null || req.session.username == '' || req.session.username == undefined){
        res.redirect('/');
    }
    res.render('client', { username: username });
})

server.listen(8888, function () {
    console.log('服务已在http://localhost:8888启动');
})

io.on('connection', function (clientSocket) {
    var username='';
    clientSocket.on('login',function(data) {
        username=data.name;
        clientSocket.broadcast.emit("enter", data);
        model.find({}, function (err, result) {
            if (err) {
                console.log(err)
            } else {
                for (var i = 0; i < result.length; i++) {
                    clientSocket.emit("receiveMsg", result[i]);
                }
            }
        })
    })

    clientSocket.on('sendMsg', function (data) {
        model.create({ name: data.name, chatInfo: data.chatInfo, time: data.time }, function (err, result) {
            if (err) {
                console.log(err)
            } else {
                console.log(result)
            }
        })
        clientSocket.broadcast.emit("receiveMsg", data);
    })
    
    clientSocket.on('disconnect', function () {
        var data = { info: username+'离开了聊天室', time: new Date().toLocaleString() }
        clientSocket.broadcast.emit("leaved", data);
    }) 
})
